package dept

import (
	"context"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/mapper/entity"

	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type SelectListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeptSelectListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SelectListLogic {
	return &SelectListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SelectListLogic) DeptSelectList(in *pb.EmptyObj) (*pb.DeptSelectListResp, error) {
	// 1.查询一级参数
	deptBO := bo.SysDeptBO{ParentId: 0}
	deptBO.HasDelFlag = true
	deptBO.DelFlag = 0
	deptMapper := mapper.NewDeptMapper()
	selectList, err := deptMapper.SelectList(l.svcCtx.DBEngin, deptBO)
	if err != nil {
		return nil, err
	}
	if len(selectList) < 1 {
		return &pb.DeptSelectListResp{}, err
	}
	// 2.递归查询子节点下面的子节点
	treeList, err := l.getDeptTreeList(deptMapper, selectList)
	if err != nil {
		return nil, err
	}
	return &pb.DeptSelectListResp{DeptArr: treeList}, nil
}

func (l *SelectListLogic) getDeptTreeList(mapper *mapper.DeptMapper, arr []entity.SysDeptEntity) ([]*pb.DeptListResp, error) {
	var subArr []*pb.DeptListResp
	if len(arr) < 1 {
		return subArr, nil
	}
	for _, v := range arr {
		sub := pb.DeptListResp{
			DeptId:   v.DeptId,
			Name:     v.Name,
			ParentId: v.ParentId,
			OrderNum: int32(v.OrderNum),
		}
		subList, err := mapper.SelectList(l.svcCtx.DBEngin, bo.SysDeptBO{
			ParentId:   v.DeptId,
			HasDelFlag: true,
			DelFlag:    0,
		})
		if err != nil {
			return nil, err
		}
		menuTreeList, err := l.getDeptTreeList(mapper, subList)
		if err != nil {
			return nil, err
		}
		sub.SubList = menuTreeList
		subArr = append(subArr, &sub)
	}
	return subArr, nil
}
